package com.zjj.wangluo.tcp;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhoujunjie
 * @desc TODO
 * @date
 */
public class TCPClient {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1" , 8888);
            System.out.println("-------TCPClient上线-------");

            //客户端  发消息  读消息
            new Thread(new ReadThread(socket , countDownLatch)).start();
            new Thread(new WriteThread(socket , countDownLatch)).start();

            //阻塞  由写线程写exit则计数器清零
            countDownLatch.await();
        } catch (ConnectException e) {
            System.out.println("服务器繁忙，请稍后重试~");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            System.exit(0);
        }
    }

}
